using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class ItemDb {	
	public const string IMAGE_DIR = "images/item_icons/";
	
	/* TODO: this should come from the db, possibly memoized */
	public static Dictionary<string, ItemInfo> ITEM_DB =
	new Dictionary<string, ItemInfo>()
	{
		{ "BerryRed",
			new ItemInfo(
				new PriceCurrency(new GoldCurrency(0)),
				ItemDb.IMAGE_DIR + "berry_red")
		},
		{ "BerryBlue",
			new ItemInfo(
				new PriceCurrency(new GoldCurrency(10)),
				ItemDb.IMAGE_DIR + "berry_blue")
		},
		{ "BerryGreen",
			new ItemInfo(
				new PriceCurrency(new GoldCurrency(20)),
				ItemDb.IMAGE_DIR + "berry_green",
				10)
		},
	};
}

public class ItemInfo {
	public readonly PriceCurrency price = null;
	public readonly string image_path;
	public readonly int max_stack_size;
	
	public ItemInfo(
		PriceCurrency price,
		string image_path=ItemDb.IMAGE_DIR + "missing",
		int max_stack_size=99) {
		this.price = price.Clone();
		this.image_path = image_path;
		this.max_stack_size = max_stack_size;
	}
}

public class ItemStack {
	public readonly Item item;
	public int amount = 1;
	
	public ItemStack(Item i, int amount=1) {
		this.item = i;
		this.amount = amount;
	}
	
	public override string ToString() {
		return this.item.ToString() + "x" + this.amount;
	}
	
	public void TakeAllFrom(ItemStack other) {
		int diff;
		int max;
		
		max = this.item.MaxStackSize();
		
		
		if (this.amount + other.amount <= max) {
			diff = other.amount;
		} else {
			diff = max - this.amount;
		}
		
		this.amount += diff;
		other.amount -= diff;
	}
	
	public int FreeCapacity() {
		int max_stack_size = this.item.MaxStackSize();
		if (max_stack_size == 0) {
			/* unstackable, there's no capacity free */
			return 0;
		} else {
			return max_stack_size - this.amount;
		}
	}
}

public class Item : IShopBuyable {
	public readonly string GameName;
	ItemInfo info = null;
	//abstract string DbName { set; get; }
	
	public Item(string name) {
		this.GameName = name;
		if (ItemDb.ITEM_DB.ContainsKey (name)) {
			this.info = ItemDb.ITEM_DB[name];
		}
	}
	
	public string DisplayName() {
		return this.GameName;
	}

	public PriceCurrency GetPrice() {
		return this.info.price.Clone();
	}
	
	public string GetImagePath() {
		return this.info.image_path;
	}
	
	public bool IsStackable() {
		return (this.MaxStackSize() > 0);
	}
	
	/* @returns: 0 means not stackable */
	public int MaxStackSize() {
		return this.info.max_stack_size;
	}
	
	public override string ToString() {
		return this.GameName;
	}
	
	public static bool CompareItemType(Item left, Item right) {
		return left.GameName.Equals(right.GameName);
	}
}

